<template>
  <div ref="bpmnContainer" class="bpmn-container"></div>
</template>

<script lang="ts" setup>
import { ref, onMounted, defineProps, defineEmits } from 'vue';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';

const props = defineProps({
  modelValue: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['update:modelValue']);

const bpmnContainer = ref<HTMLElement>();
let bpmnModeler: BpmnModeler;
const initialXml = `
  <?xml version="1.0" encoding="UTF-8"?>
  <bpmn:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" id="Definitions_0qfn39m" targetNamespace="http://bpmn.io/schema/bpmn" exporter="bpmn-js (https://demo.bpmn.io)" exporterVersion="18.0.0">
    <bpmn:process id="Process_1recb87" isExecutable="false">
      <bpmn:startEvent id="StartEvent_1nrci5k" />
    </bpmn:process>
    <bpmndi:BPMNDiagram id="BPMNDiagram_1">
      <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1recb87">
        <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1nrci5k">
          <dc:Bounds x="156" y="82" width="36" height="36" />
        </bpmndi:BPMNShape>
      </bpmndi:BPMNPlane>
    </bpmndi:BPMNDiagram>
  </bpmn:definitions>
  `;


onMounted(async () => {
  if (!bpmnContainer.value) {
    console.error('bpmnContainer is not mounted');
    return;
  }

  bpmnModeler = new BpmnModeler({
    container: bpmnContainer.value,
    additionalModules: [],
    moddleExtensions: {}
  });

  // 初始化模型
  const xml = props.modelValue || initialXml;
  emit('update:modelValue', xml);

  try {
    await bpmnModeler?.importXML(xml);
  } catch (error) {
    console.error('Error importing XML:', error);
  }

  // 监听模型变化
  bpmnModeler?.on('commandStack.changed', async () => {
    const result = await bpmnModeler?.saveXML({ format: true });
    emit('update:modelValue', result?.xml);
  });
});
</script>

<style scoped>
.bpmn-container {
  height: 100%;
  width: 100%;
  position: relative; /* 确保容器具有正确的布局 */
}
</style>